﻿using HHXX.IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace HHXX.BLL
{
    public abstract class BaseService<T> where T : class, new()
    {

        #region 属性
        /// <summary>
        /// 强迫子类给父类的 这个属性赋值 才可以调用下面的方法
        /// </summary>
        public IBaseDal<T> CurrentDal { get; set; }
        /// <summary>
        /// 数据库访问层对数据库的一次会话
        /// </summary>
        public IDbSession DbSession { get; set; } 
        #endregion

        #region select
        public T GetModel(int id)
        {
            return CurrentDal.GetModel(id);
        }
        public T GetModel(object id)
        {
            return CurrentDal.GetModel(id);
        }
        public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda)
        {
            return CurrentDal.GetEntities(whereLambda);
        }
        public IQueryable<T> GetPageEntities<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda
            , Expression<Func<T, S>> orderByLambda, bool isAsc)
        {
            return CurrentDal.GetPageEntities(pageSize, pageIndex, out total, whereLambda, orderByLambda, isAsc);
        }
        #endregion

        #region cud
        public T Add(T entity)
        {
            CurrentDal.Add(entity);
            DbSession.SaveChanges();
            return entity;
        }
        public bool Update(T entity)
        {
            CurrentDal.Update(entity);
            return DbSession.SaveChanges() > 0;
        }
        public bool Delete(T entity)
        {
            CurrentDal.Delete(entity);
            return DbSession.SaveChanges() > 0;
        }
        public bool IsExist(object id)
        {
            return CurrentDal.IsExist(id);
        }
        public bool Delete(int id)
        {
            CurrentDal.Delete(id);
            return DbSession.SaveChanges() > 0;
        }
        /// <summary>
        /// 批量真删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DeleteList(List<int> ids)
        {
            foreach (var id in ids)
            {
                CurrentDal.Delete(id);
            }
            return DbSession.SaveChanges();
        }
        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DeleteListByLogical(List<int> ids)
        {
            CurrentDal.DeleteListByLogical(ids);
            return DbSession.SaveChanges();
        }

        #endregion

    }
}
